//
//  MainTabbarController.m
//  smartVillageApp
//
//  Created by Jabez on 25/4/15.
//  Copyright (c) 2015 ihome023.com All rights reserved.
//

#import "MainTabbarController.h"
#import "BarItemAnimation.h"
#import "MeViewController.h"
#import "LoginViewController.h"
#import "MerchantsViewController.h"
#import "PurchaseCarViewController.h"
#import "NotLoggedInViewController.h"

#import "HomeViewController.h"
#import "ShareUserModel.h"
#import "BaseUrlConfig.h"

#import "Common.h"

@interface MainTabbarController ()
{
    
    EAIntroView * intro;
    
    NSArray *arrItems_;
    NSArray *arrImgNormal_;
    NSArray *arrImgHight_;
    
    NSInteger indexSelect_;
    
    
    
    HomeViewController *homeControl_;
    MerchantsViewController *MerchantsView_;
    MeViewController *MeViewCtn_;
    PurchaseCarViewController *  PurchaseCar_;

    
    NSMutableArray *arrTabControllers_;
}

@end

@implementation MainTabbarController

static MainTabbarController *mainTabbarController_;


#pragma mark - life style



+(MainTabbarController *)ShareTabBarController
{
    @synchronized(self)
    {
        if (!mainTabbarController_)
        {
            mainTabbarController_=  [[MainTabbarController alloc] initWithNibName:@"MainTabbarController" bundle:nil];


        }
    }
    
    return mainTabbarController_;
}
-(void)viewWillAppear:(BOOL)animated
{


}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    arrTabControllers_ = [[NSMutableArray alloc] init];
    [self InitItems];

        //默认选中imagehome

    [self SelectTab:0];


}
- (void)showIntroWithCrossDissolve {
    
    [[Common getUserDefaults]setObject:@"yes" forKey:@"home"];
    EAIntroPage *page1 = [EAIntroPage page];
    page1.bgImage = [UIImage imageNamed:@"引导1"];
    EAIntroPage *page2 = [EAIntroPage page];
    page2.bgImage = [UIImage imageNamed:@"引导页2"];
    EAIntroPage *page3 = [EAIntroPage page];
    page3.bgImage = [UIImage imageNamed:@"引导页3"];
    
    
    intro = [[EAIntroView alloc] initWithFrame:mainTabbarController_.view.bounds andPages:@[page1,page2,page3]];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundColor:[UIColor clearColor]];
    [btn setBackgroundImage:[UIImage imageNamed:@"引导页-按扭"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"引导页-按扭"] forState:UIControlStateHighlighted];
    [btn setFrame:CGRectMake((winSize.width-85)/2, [UIScreen mainScreen].bounds.size.height-60, 86, 40)];
    intro.pageControl.frame = CGRectMake(0, mainTabbarController_.view.frame.size.height-30, mainTabbarController_.view.frame.size.width, 20);
    btn.hidden=YES;
    intro.skipButton = btn;
    
    [btn addTarget:self action:@selector(introDidFinish) forControlEvents:UIControlEventTouchUpInside];
    [intro setDelegate:self];
    [intro showInView:mainTabbarController_.view animateDuration:0.0];
    [mainTabbarController_.view bringSubviewToFront:intro];
    
}
- (void)introDidFinish;
{
    _TopLine.hidden  = NO;
    
    _vMainContent.hidden =NO;


}
-(void)viewDidAppear:(BOOL)animated
{
    [self checkIsUserLogin];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - controller events
-(void)checkIsUserLogin
{
    //如果未登录，只能停留在主页
    ShareUserModel * user = [ShareUserModel shareUserModel];
    if (!user.isLogined) {
        [self TapButtons:_btnHome];
    }
}


-(BOOL)SelectTab:(NSInteger)index
{
    BOOL bResult = NO;
    
    [self SetTabEnable:NO];
    
    
//    需要登录的选项
    if (index > 0 && (![self CheckLoginStatus])) {
        goto end_Selection;
    }

    
    
    //隐去所有显示
    for (UIViewController *controller in arrTabControllers_) {
        controller.view.hidden = YES;
    }
    

    
    switch (index)
    {
        case 0:
            if (!homeControl_) {
                homeControl_=[[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
                [self addControllerToTab:homeControl_];
            }
            homeControl_.view.hidden = NO;
            bResult = YES;
            
            break;
        case 1:
        {
        
                    if (!MerchantsView_) {
                        MerchantsView_=[[MerchantsViewController alloc] initWithNibName:@"MerchantsViewController" bundle:nil];
                        [self addControllerToTab:MerchantsView_];
                    }
                    MerchantsView_.view.hidden = NO;
                    bResult = YES;

                }
        
            break;
        case 2:
            
            if (!MeViewCtn_) {
                MeViewCtn_=[[MeViewController alloc] init];
                [self addControllerToTab:MeViewCtn_];
            }
            MeViewCtn_.view.hidden = NO;
            bResult = YES;
            break;
        case 3:
            
            if (!PurchaseCar_) {
                PurchaseCar_ = [[PurchaseCarViewController alloc] initWithNibName:@"PurchaseCarViewController" bundle:Nil];
                [self addControllerToTab:PurchaseCar_];
            }
            PurchaseCar_.view.hidden = NO;
            bResult = YES;
            break;
            
        default:
            break;
    }
end_Selection:
    [self SetTabEnable:YES];
    return bResult;
}


#pragma mark - allMethod for item bar
-(BOOL)CheckLoginStatus
{
    BOOL bLogined = NO;
    
    ShareUserModel * userShare = [ShareUserModel shareUserModel];
    bLogined = userShare.isLogined;
    bLogined =YES;
//    userShare.isLogined = YES;
    if (!userShare.isLogined)
    {
        NotLoggedInViewController *  NotLoggedInView  =[[NotLoggedInViewController alloc] initWithNibName:@"NotLoggedInViewController" bundle:nil];
        [self presentViewController: NotLoggedInView animated:NO completion:NULL];
    }

    
    return bLogined;
}


-(void)addControllerToTab:(UIViewController *)controller
{
    [controller.view setFrame:self.vMainContent.frame];
    [self addChildViewController:controller];
    
    [self.vMainContent addSubview:controller.view];
    [arrTabControllers_ addObject:controller];
}


-(void)SetTabEnable:(BOOL)enable
{
    for (UIButton *button in arrItems_) {
        button.enabled = enable;
    }
}


-(void)InitItems
{
    // Do any additional setup after loading the view from its nib.
    arrItems_ = [[NSArray alloc] initWithObjects:_btnHome,_btnMerchants,_btnMe,_btnPurchaseCar, nil];
    

    
    
    arrImgHight_ =
    [[NSArray alloc] initWithObjects:
     [UIImage imageNamed:@"message_selected"],
     [UIImage imageNamed:@"imageHightMerchants"],
     [UIImage imageNamed:@"setting_selected"],
     [UIImage imageNamed:@"imageHightPurchaseCar"],nil];
    
    arrImgNormal_=
    [[NSArray alloc] initWithObjects:
     [UIImage imageNamed:@"imagehome"],
     [UIImage imageNamed:@"imageMerchants"],
     [UIImage imageNamed:@"imageMe"],
     [UIImage imageNamed:@"imageGrayPurchaseCar"],nil];
    
    NSArray *arrTitle = [[NSArray alloc] initWithObjects:@"首页",@"商家",@"我的",@"购物车", nil];

    indexSelect_ = 0;
    for (int i=0; i<arrItems_.count; i++)
    {
        BarItemAnimation *button = [arrItems_ objectAtIndex:i];
        
        if (i==indexSelect_) {
            [button.lalTitle setTextColor:[UIColor colorWithRed:68.0/0xff green:192.0/0xff blue:250.0/0xff alpha:1]];
            [button.imvMain setImage:[arrImgHight_ objectAtIndex:i]];
        }else
        {
            [button.imvMain setImage:[arrImgNormal_ objectAtIndex:i]];
            [button.lalTitle setTextColor:[UIColor colorWithRed:153.0/0xff green:153.0/0xff blue:153.0/0xff alpha:1]];
        }
        
        
        button.imHight  = [arrImgHight_ objectAtIndex:i];
        button.imNormal = [arrImgNormal_ objectAtIndex:i];
        
        [button.lalTitle setText:[arrTitle objectAtIndex:i]];
        button.tag = i;
        
        [button addTarget:self action:@selector(TapButtons:) forControlEvents:UIControlEventTouchUpInside];
    }
}

-(void)TapButtons:(UIButton *)sender
{
    if (indexSelect_ == sender.tag) {
        return;
    }
    
    if ([self SelectTab:sender.tag]) {
        [self UpdateItemsStatus:sender.tag];
        indexSelect_ = sender.tag;
    }
    
}


-(void)UpdateItemsStatus:(NSInteger)selected
{
    
    
    for (int i=0; i<arrItems_.count; i++)
    {
        BarItemAnimation *button = [arrItems_ objectAtIndex:i];
        
        if (i==selected)
        {
            [button.lalTitle setTextColor:[UIColor colorWithRed:68.0/0xff green:192.0/0xff blue:250.0/0xff alpha:1]];
            [button.imvMain setImage:[arrImgHight_ objectAtIndex:i]];
            [button PlayAnimation];
        }else
        {
            [button.lalTitle setTextColor:[UIColor colorWithRed:153.0/0xff green:153.0/0xff blue:153.0/0xff alpha:1]];
            [button.imvMain setImage:[arrImgNormal_ objectAtIndex:i]];
        }
        [button setNeedsLayout];
        [button layoutIfNeeded];
        
    }
    
    
}

-(void)showMessage:(NSString *)message
{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor blackColor];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(290, 9000)];
    label.frame = CGRectMake(10, 5, LabelSize.width, LabelSize.height);
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    [showview addSubview:label];
    showview.frame = CGRectMake((__MainScreen_Width - LabelSize.width - 20)/2, __MainScreen_Height/2, LabelSize.width+20, LabelSize.height+10);
    [UIView animateWithDuration:3.0 animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
}

/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
@end
